package org.springframework.sandbox.nettymvc;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.util.concurrent.EventExecutorGroup;

import javax.servlet.http.HttpServletResponse;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;

public class FullHttpResponseToStringEncoder extends
        MessageToByteEncoder<HttpResponse> {

    private static final AtomicLong aid=new AtomicLong(1);
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, HttpResponse httpResponse, ByteBuf byteBuf) throws Exception {
        String msg="hello";
        DefaultHttpResponse defaultHttpResponse=(DefaultHttpResponse)httpResponse;
        //msg=defaultHttpResponse.getDecoderResult().toString();

//        HttpServletResponse httpServletResponse=(HttpServletResponse)httpResponse;
        //httpServletResponse.getOutputStream()

        Response response =new Response();
        response.setId(aid.incrementAndGet());
        response.setResult(msg);
        //把响应结果返回给客户端
        //channelHandlerContext.channel().write(JSONObject.toJSONString(response));
        //channelHandlerContext.channel().unsafe().flush();
        byteBuf.writeBytes(ByteBufUtil.encodeString(channelHandlerContext.alloc(), CharBuffer.wrap(JSONObject.toJSONString(response)), Charset.defaultCharset()));
    }
}
